﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using OTS.BLL;
using System.Data;
using OTS.Model;
using System.Xml;

public partial class OLPC_MCToInvoice : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            CommonMethod.IsTimeOutUserCode(this, CommonModel.errorTimeOutUrl1);
            SettingRight();
            Session["dtlist"] = null;
            Session["assigneddt"] = null;
            InitUi();
            tc2.ActiveTabIndex = 0;
        }
    }
    // 页面权限
    private void SettingRight()
    {
        bool[] rightlist = SysRightBLL.GetRightByType(new string[] { 
            Session["UserCode"].ToString(), 
            Session["CoCode"].ToString(), 
            "mctoinvoice"});
        if (!rightlist[0])
        { this.Page.Response.Write(String.Format("<script language='javascript'>window.parent.location.href='{0}';</script>", CommonModel.loginOut1)); }

        gv.Columns[0].Visible = rightlist[1];
        gvAssigned.Columns[1].Visible = rightlist[2];
        gvAssigned.Columns[2].Visible = rightlist[3];
        btnadd.Visible = rightlist[1];
    }

    // 初始化绑定
    private void InitUi()
    {
        CommonMethod.IsTimeOutUserCode(this, CommonModel.errorTimeOutUrl1);
        InitDataBind();
        InitAssignedDataBind();
    }
    // 已有数据
    private void InitDataBind()
    {
        DataTable tempdt = new DataTable();
        if (Session["dtlist"] != null)
        {
            tempdt = Session["dtlist"] as DataTable;
        }
        else
        {
            tempdt = AccountStatementManualBLL.GetList(" len(isnull(InvioceNo,''))=0 and StateValue<2 ");
            gv.DataSource = tempdt;
            gv.DataBind();
        }
        gv.DataSource = tempdt;
        gv.DataBind();
        Session["dtlist"] = tempdt;
        tempdt = null;
    }
    // 已匹配收款数据
    private void InitAssignedDataBind()
    {
        DataTable tempdt = new DataTable();
        if (Session["assigneddt"] != null)
        {
            tempdt = Session["assigneddt"] as DataTable;
        }
        else
        {
            tempdt = AccountStatementManualBLL.GetList(" len(isnull(InvioceNo,''))>0 ");
            gvAssigned.DataSource = tempdt;
            gvAssigned.DataBind();
        }
        gvAssigned.DataSource = tempdt;
        gvAssigned.DataBind();
        Session["assigneddt"] = tempdt;
    }

    protected void gv_AfterPerformCallback(object sender, 
        DevExpress.Web.ASPxGridView.ASPxGridViewAfterPerformCallbackEventArgs e)
    {
        InitDataBind();
    }

    // 匹配行事件
    protected void gv_RowCommand(object sender, 
        DevExpress.Web.ASPxGridView.ASPxGridViewRowCommandEventArgs e)
    {
        try
        {
            string temp = e.CommandArgs.CommandArgument.ToString();
            int Inttemp = int.Parse(temp);
            string cmd = e.CommandArgs.CommandName;
            if (cmd == "assigning")
            {
                AssignedOrViewBind(1, e.KeyValue.ToString());
            }
        }
        catch (Exception ex)
        {
            Log.WritLog("gv_RowCommand:", ex.ToString());
        }
    }

    private void Clear()
    {
        txtContractNo.Text = "";
        txtSalesOrderNo.Text = "";
        txtSalesOrderAmountVAT.Text = "0";
        txtCAppliedAmount.Text = "0";
        txtOAppliedAmount.Text = "0";
        txtSalesman.Text = "";
        txtCASO.Text = "0";
        txtApplyAmount.Text = "";
        txtCustomerCode.Text = "";
        txtCustomer.Text = "";
        txtCollectionType.Text = "";
        //txtUnallocatedBalance.Text = "";
        txtApplyDate.Text = "";
        txtApplyPerson.Text = "";
        gvInvoice.DataSource = null;
        gvInvoice.DataBind();
    }

    protected void gvAssigned_AfterPerformCallback(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewAfterPerformCallbackEventArgs e)
    {
        InitAssignedDataBind();
    }
    protected void gvAssigned_RowCommand(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewRowCommandEventArgs e)
    {
        try
        {
            string temp = e.CommandArgs.CommandArgument.ToString();
            string id = e.KeyValue.ToString();
            string cmd = e.CommandArgs.CommandName;
            if (cmd == "view")
            {
                // 查看
                AssignedOrViewBind(0, id);
            }
            else if (cmd == "edit")
            {
                // 编辑
                AssignedOrViewBind(2, id);
            }
            else if (cmd == "delete")
            {
                #region 删除

                bool resultFlag = MCToInvoiceBLL.Delete(long.Parse(id));
                string message = "删除失败！";
                if (resultFlag)
                {
                    Session["assigneddt"] = null;
                    Session["dtlist"] = null;
                    InitDataBind();
                    InitAssignedDataBind();
                    message = "删除成功!";
                }
                CommonMethod.regAlertMessage(upd, message, this);

                #endregion
            }
        }
        catch (Exception ex)
        {
            Log.WritLog("gvAssigned_RowCommand:", ex.ToString());
        }
    }
    // 已匹配收款编辑、查看绑定
    private void AssignedOrViewBind(int actionflag, string id)
    {
        Clear();
        btnadd.Visible = false;
        btnedit.Visible = false;

        #region

        AccountStatementManualModel model = new AccountStatementManualModel();
        model = AccountStatementManualBLL.GetModel(long.Parse(id));

        if (model != null
            && model.ContractNo != null && model.ContractNo.Trim().Length > 0
            && model.SalesOrderNo != null && model.SalesOrderNo.Trim().Length > 0)
        {
            txtContractNo.Text = model.ContractNo;
            txtSalesOrderNo.Text = model.SalesOrderNo;
            DataTable tpdt = AccountStatementManualBLL.GetContractOrderInfo(model.ContractNo, model.SalesOrderNo);
            if (tpdt != null && tpdt.Rows.Count > 0)
            {
                DataRow row = tpdt.Rows[0];
                txtSalesOrderAmountVAT.Text = row["OrderValue"].ToString();
                txtSalesman.Text = row["SalesName"].ToString();
                txtCustomerCode.Text = row["CustomerNo"].ToString();
                txtCustomer.Text = row["CustomerName"].ToString();
                txtCAppliedAmount.Text = row["CAppliedAmount"].ToString();
                txtOAppliedAmount.Text = row["OAppliedAmount"].ToString();
                txtCEName.Text = row["CEName"].ToString();
            }

            txtCASO.Text = model.CollectionAgainstSalesman;
            txtApplyAmount.Text = model.ApplyAmount.ToString();
            txtCollectionType.Text = model.CollectionType;
            //txtUnallocatedBalance.Text = model.UnallocatedBalance;
            txtApplyDate.Text = DateTime.Parse(model.UPDATEDATE).ToString("yyyy-MM-dd HH:mm:ss");
            txtApplyPerson.Text = model.ApplyPerson;

            gvInvoice.Columns[gvInvoice.Columns.Count - 2].Visible = false;
            gvInvoice.Columns[gvInvoice.Columns.Count - 1].Visible = false;
            DataTable csInvoicedt = new DataTable();
            if (actionflag == 0)
            {
                csInvoicedt = MCToInvoiceBLL.GetCSInvoice(id);
                gvInvoice.Columns[gvInvoice.Columns.Count - 1].Visible = true;
            }
            else if (actionflag == 1)
            {
                csInvoicedt = MCToInvoiceBLL.GetCSInvoice(actionflag, model.ContractNo, model.SalesOrderNo);
                btnadd.Visible = true;
                gvInvoice.Columns[gvInvoice.Columns.Count - 2].Visible = true;
            }
            else if (actionflag == 2)
            {
                csInvoicedt = MCToInvoiceBLL.GetCSInvoice(actionflag, model.ContractNo, model.SalesOrderNo);
                btnedit.Visible = actionflag == 2 ? true : false;
                gvInvoice.Columns[gvInvoice.Columns.Count - 2].Visible = true;
            }
            gvInvoice.DataSource = csInvoicedt;
            gvInvoice.DataBind();
            if (actionflag == 1)
            {
                // 申请匹配金额
                float applyamount = float.Parse(txtApplyAmount.Text);
                float invoiceselectedamount = 0;
                bool otherscheckflag = true;
                for (int i = 0; i < gvInvoice.Rows.Count; i++)
                {
                    CheckBox ChkSelect = gvInvoice.Rows[i].FindControl("chkitem") as CheckBox;
                    TextBox txt = gvInvoice.Rows[i].FindControl("txtInvoiceAmount") as TextBox;
                    if (otherscheckflag)
                    {
                        invoiceselectedamount += float.Parse(txt.Text);
                        ChkSelect.Checked = otherscheckflag;
                        if (invoiceselectedamount > applyamount)
                        {
                            txt.Text = (float.Parse(txt.Text) - invoiceselectedamount + applyamount).ToString();
                            otherscheckflag = false;
                            if (txt.Text.Trim() == "0")
                                ChkSelect.Checked = false;
                            break;
                        }
                    }
                }
            }
            else if (actionflag == 2)
            {
                csInvoicedt = MCToInvoiceBLL.GetCSInvoice(id);
                for (int i = 0; i < gvInvoice.Rows.Count; i++)
                {
                    DataRow[] rows = csInvoicedt.Select(string.Format("InvoiceNo='{0}'", gvInvoice.Rows[i].Cells[1].Text));
                    if (rows != null && rows.Length > 0)
                    {
                        CheckBox chk = gvInvoice.Rows[i].FindControl("chkitem") as CheckBox;
                        TextBox txt = gvInvoice.Rows[i].FindControl("txtInvoiceAmount") as TextBox;
                        chk.Checked = true;
                        txt.Text = rows[0]["Amount"].ToString();
                    }
                }
            }
            hidAccountStatementManualID.Value = id;

            tc2.ActiveTabIndex = 2;            
        }

        #endregion        
    }
    
    protected void gvInvoiceChkHead_CheckedChanged(object sender, EventArgs e)
    {
        CheckBox chk = sender as CheckBox;
        bool chkflag = chk.Checked;
        for (int i = 0; i < gvInvoice.Rows.Count; i++)
        {
            CheckBox ChkSelect = gvInvoice.Rows[i].FindControl("chkitem") as CheckBox;
            ChkSelect.Checked = chkflag;
        }
    }
    private bool Check()
    {
        if (string.IsNullOrEmpty(txtContractNo.Text.Trim()))
        {
            CommonMethod.regAlertMessage(upd, "合同号不能为空！ ", this);
            return false;
        }
        else if (string.IsNullOrEmpty(txtSalesOrderNo.Text.Trim()))
        {
            CommonMethod.regAlertMessage(upd, "订单号不能为空！ ", this);
            return false;
        }
        else if (string.IsNullOrEmpty(txtApplyAmount.Text.Trim()))
        {
            CommonMethod.regAlertMessage(upd, "申请金额不能为空！ ", this);
            return false;
        }
        else if (!CommonMethod.CheckNUM(txtApplyAmount.Text.Trim()))
        {
            CommonMethod.regAlertMessage(upd, "申请匹配金额必须为数字！ ", this);
            return false;
        }
        else if (txtApplyAmount.Text.Trim() == "0")
        {
            CommonMethod.regAlertMessage(upd, "申请匹配金额不能为： 0 ", this);
            return false;
        }// 申请匹配金额
        float applyamount = float.Parse(txtApplyAmount.Text);
        float invoiceselectedamount = 0;
        bool otherscheckflag = true;
        for (int i = 0; i < gvInvoice.Rows.Count; i++)
        {
            CheckBox ChkSelect = gvInvoice.Rows[i].FindControl("chkitem") as CheckBox;
            TextBox txt = gvInvoice.Rows[i].FindControl("txtInvoiceAmount") as TextBox;
            if (ChkSelect.Checked && otherscheckflag)
            {
                invoiceselectedamount += float.Parse(txt.Text);
                if (invoiceselectedamount > applyamount)
                {
                    txt.Text = (float.Parse(txt.Text) - invoiceselectedamount + applyamount).ToString();
                    otherscheckflag = false;
                }
            }
            else
            {
                ChkSelect.Checked = otherscheckflag;
                txt.Text = "0";
            }
        }
        if (applyamount > invoiceselectedamount)
        {
            CommonMethod.regAlertMessage(upd, "已选发票金额不能小于申请匹配金额！ ", this);
            return false;
        }
        return true;
    }

    private List<MCToInvoiceModel> SetModel()
    {
        List<MCToInvoiceModel> listmodel = new List<MCToInvoiceModel>();
        MCToInvoiceModel model = new MCToInvoiceModel();
        model.AccountStatementManualID = long.Parse(hidAccountStatementManualID.Value);
        model.ADDDATE = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
        model.ADDAUTHOR = Session["UserCode"] == null ? "10000" : Session["UserCode"].ToString();
        model.UPDATEDATE = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
        model.UPDATEAUTHOR = Session["UserCode"] == null ? "10000" : Session["UserCode"].ToString();

        for (int i = 0; i < gvInvoice.Rows.Count; i++)
        {
            CheckBox ChkSelect = gvInvoice.Rows[i].FindControl("chkitem") as CheckBox;
            TextBox txt = gvInvoice.Rows[i].FindControl("txtInvoiceAmount") as TextBox;
            if (ChkSelect.Checked && txt.Text != "0")
            {
                MCToInvoiceModel tempmodel = new MCToInvoiceModel();
                tempmodel = model;
                tempmodel.InvoiceNo = gvInvoice.Rows[i].Cells[1].Text;
                tempmodel.InvoiceAmount = decimal.Parse(gvInvoice.Rows[i].Cells[2].Text.ToString());
                tempmodel.InvBalance = decimal.Parse(gvInvoice.Rows[i].Cells[3].Text);
                tempmodel.Amount = decimal.Parse(txt.Text);
                tempmodel.Remarks = "";
                listmodel.Add(tempmodel);
            }
        }

        return listmodel;
    }
    protected void btnadd_Click(object sender, EventArgs e)
    {
        CommonMethod.IsTimeOutUserCode(this, CommonModel.errorTimeOutUrl1);
        bool flag = Check();
        if (flag)
        {
            List<MCToInvoiceModel> listmodel = SetModel();
            string message = "添加失败！";
            bool resultFlag = MCToInvoiceBLL.Add(listmodel);

            if (resultFlag)
            {
                Session["assigneddt"] = null;
                Session["dtlist"] = null;
                InitDataBind();
                InitAssignedDataBind();
                message = "添加成功!";
                Clear();
                tc2.ActiveTabIndex = 1;
            }
            CommonMethod.regAlertMessage(upd, message, this);
        }
    }
    protected void btnedit_Click(object sender, EventArgs e)
    {
        CommonMethod.IsTimeOutUserCode(this, CommonModel.errorTimeOutUrl1);
        bool flag = Check();
        if (flag)
        {
            List<MCToInvoiceModel> listmodel = SetModel();
            bool resultFlag = MCToInvoiceBLL.Add(listmodel);
            string message = "保存失败！";

            if (resultFlag)
            {
                Session["assigneddt"] = null;
                Session["dtlist"] = null;
                InitDataBind();
                InitAssignedDataBind();
                message = "保存成功!";
                tc2.ActiveTabIndex = 1;
                Clear();
                btnedit.Visible = false;
                btnadd.Visible = gv.Columns[0].Visible;
            }
            CommonMethod.regAlertMessage(upd, message, this);
        }
    }

    #region 数据导出

    protected void btnMathingExport_Click(object sender, EventArgs e)
    {
        InitDataBind();

        gv.Columns[0].Visible = false;
        gv.Columns[1].Visible = false;
        gridready.WriteXlsToResponse();
        gv.Columns[0].Visible = true;
        gv.Columns[1].Visible = true;
    }
    protected void btnMathedExport_Click(object sender, EventArgs e)
    {
        InitAssignedDataBind();

        gvAssigned.Columns[0].Visible = false;
        gvAssigned.Columns[1].Visible = false;
        gvAssigned.Columns[2].Visible = false;
        gvAssigned.Columns[3].Visible = false;
        gridreadied.WriteXlsToResponse();
        gvAssigned.Columns[0].Visible = true;
        gvAssigned.Columns[1].Visible = true;
        gvAssigned.Columns[2].Visible = true;
        gvAssigned.Columns[3].Visible = true;
    }

    #endregion

    #region Checked

    public bool IsVisibale(string statevalue)
    {
        return "1" == statevalue;
    }
    public bool CreditChecked(string CreditCheck)
    {
        return "1" == CreditCheck;
    }
    public string OnblurCheck(string invbalance)
    {
        return string.Format("txtIsNumberOnly(this.id);NotBigger(this.id,{0});", invbalance);
    }
    public string DataFormat(string date)
    {
        string temp = date;
        try
        {
            temp = DateTime.Parse(date).ToString("yyyy-MM-dd");
            //if (!string.IsNullOrEmpty(temp) && temp.Length > 10)
            //    temp = temp.Substring(0, 10);
        }
        catch (Exception ex)
        {
            Log.WritLog("DataFormat:", ex.ToString());
        }
        return temp;
    }

    #endregion
    
    
}